//
//  WBNetworkManager.swift
//  传智微博
//
//  Created by Pro on 2017/8/11.
//  Copyright © 2017年 liuyanwei. All rights reserved.
//

import UIKit
import AFNetworking

//swift 枚举支持任意数据类型
enum WBHTTPMethod {
    case GET
    case POST
}

//网络管理工具
class WBNetworkManager: AFHTTPSessionManager {

    //静态区（常量去）/常量/闭包
    //第一次访问时执行闭包，并将结果保存在 shared 常量中
    static let shared = WBNetworkManager()
    
    //访问令牌，所有网络请求，都基于此令牌，除了登录
    //为了保护用户安全，token有时限,默认用户是三天
    var accessToken:String? = nil  //"2.00v4p8YGoBpkmDdeb6722ae6L8v_eE"

    var uid:String? = "5365823342"

    //用户登录标记
    var userLogon : Bool {
        return accessToken != nil
    }


    //专门负责拼接token 的网络请求方法
    func tokenRequest(method:WBHTTPMethod = .GET, URLString:String, parameters: [String:AnyObject]?, competion:@escaping (_ json: Any?, _ isSuccess:Bool) -> ()) {
        
        //处理token字典
        //判断参数字典是否存在，如果为nil, 则新建
        
        guard let token = accessToken else {
            print("没有token,需要登录")
            // FIXME: 发送通知（提示用户登录）
            competion(nil,false)
            return
        }
        var parameters = parameters
        if parameters == nil {
            parameters = [String:AnyObject]()
        }
        parameters?["access_token"] = token as AnyObject
        
        //调起 request 发起真正的网络请求
        request(method: method, URLString: URLString, parameters: parameters, competion: competion)
    }
    
    /// 封装AFN的GET/POST请求
    ///
    /// - Parameters:
    ///   - method:  GET、POST
    ///   - URLString: 链接
    ///   - parameters: 参数字典
    ///   - competion: 完成回调
    func request(method:WBHTTPMethod = .GET, URLString:String, parameters: [String:AnyObject]?, competion:@escaping (_ json: Any?, _ isSuccess:Bool) -> ()) {
        
        let success = { (task:URLSessionDataTask,json:Any?)->() in
            competion(json,true)
        }
        
        let failure = {  (task:URLSessionDataTask?,error:Error)->() in
            
            if  (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token过期")
                // FIXME: 发送通知，提示用户再次登录（本方法不知道谁被调用，谁接收到通知，谁处理）
            }
            print("网络请求错误\(error)")
            competion(nil,false)
        }
        
        if method == .GET {
           get(URLString, parameters: parameters, progress: nil,  success: success , failure: failure)
        }else {
           post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
    
   
    
}
